<template>
  <div class="app-container">
    <el-tooltip
      class="item"
      effect="dark"
      :content="$t('goods.addProductTip')"
      placement="top-start"
    >
      <el-button
        class="addBtn"
        type="primary"
        icon="el-icon-plus"
        @click="addProduct"
        >{{ $t("goods.addProduct") }}</el-button
      >
    </el-tooltip>
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline sp_between"
      style="flex-wrap: nowrap"
    >
      <div>
        <el-form-item :label="$t('goods.productName')">
          <el-input v-model="formInline.name" />
        </el-form-item>
        <el-form-item :label="$t('goods.productType')">
          <el-select v-model="formInline.type">
            <el-option
              v-for="(item, index) in types"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('goods.productGroup')">
          <el-select v-model="formInline.groupId" @change="changeGroup">
            <el-option
              v-for="(item, index) in productGroupList"
              :key="index"
              :label="item.groupName"
              :value="item.productIds"
            />
          </el-select>
        </el-form-item>
      </div>
      <div>
        <el-form-item>
          <el-button
            plain
            type="primary"
            icon="el-icon-search"
            @click="onSubmit"
            >{{ $t("goods.search") }}</el-button
          >
        </el-form-item>
      </div>
    </el-form>
    <div>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane :label="$t('goods.status')" name="status" />
        <el-tab-pane :label="$t('goods.status0')" name="status0" />
        <el-tab-pane :label="$t('goods.status1')" name="status1" />
        <el-tab-pane :label="$t('goods.status3')" name="status3" />
        <!-- <el-tab-pane :label="$t('goods.status2')" name="status2" /> -->
      </el-tabs>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        fixed
        :default-sort="{ prop: 'address', order: 'descending' }"
      >
        <el-table-column :label="$t('goodsTable.picture')">
          <template slot-scope="scope">
            <el-image
              v-if="(scope.row.img + '').length < 20"
              fit="contain"
              style="width: 100px; height: 100px"
              :src="lockImgs[scope.row.img]"
            />
            <el-image
              v-else
              fit="contain"
              style="width: 100px; height: 100px"
              :src="scope.row.img"
            />
          </template>
        </el-table-column>

        <el-table-column prop="name" :label="$t('goodsTable.name')">
          <template slot-scope="scope">
            <el-input
              v-if="scope.row.editName"
              v-model="scope.row.name"
              v-focus
              size="small"
              style="width: 180px"
              @blur="blurInput('name', scope.row)"
            />
            <span v-else>{{ scope.row.name }}</span>
            <el-button type="text" @click="tableDbEdit(scope.row, 'name')"
              ><i class="el-icon-edit"
            /></el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="type"
          :label="$t('goodsTable.type')"
          show-overflow-tooltip
        >
          <template slot-scope="scope">{{
            scope.row.type ? scope.row.type.label : ""
          }}</template>
        </el-table-column>
        <el-table-column prop="price" :label="$t('goodsTable.price')">
          <template slot-scope="scope">
            <el-input
              v-if="scope.row.editPrice"
              v-model="scope.row.price"
              v-focus
              size="small"
              style="width: 80px"
              @blur="blurInput('price', scope.row)"
            />
            <span v-else style="color: #f56c6c">${{ scope.row.price }}</span>
            <el-button type="text" @click="tableDbEdit(scope.row, 'price')"
              ><i class="el-icon-edit"
            /></el-button>
          </template>
        </el-table-column>
        <el-table-column prop="status" :label="$t('goodsTable.status')">
          <template slot-scope="scope">{{
            scope.row.status ? scope.row.status.label : ""
          }}</template>
        </el-table-column>
        <el-table-column
          prop="time"
          :label="$t('goodsTable.operationTime')"
          width="180"
        >
          <template slot-scope="scope">{{ timeWord(scope.row.time) }}</template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('goodsTable.operation')">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              :content="
                scope.row.status.label !== 'On sale'
                  ? $t('goodsTable.onSaleTip')
                  : $t('goodsTable.offSaleTip')
              "
              placement="top-start"
            >
              <el-button size="mini" type="text" @click="seeDetail(scope.row)">
                {{
                  scope.row.status.label !== "On sale"
                    ? $t("goodsTable.onSale")
                    : $t("goodsTable.offSale")
                }}
              </el-button>
            </el-tooltip>

            <el-button
              size="mini"
              type="text"
              @click="editProduct(scope.row.id)"
              >{{ $t("goodsTable.edit") }}</el-button
            >
            <!-- <el-button size="mini" type="text">{{ $t('goodsTable.delete') }}</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="block cz_center">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="formInline.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <span class="pageText"> {{ $t("pagination.page") }} </span>
      </div>
    </div>
  </div>
</template>
<script>
import { getCommodityList, saveCommodity } from "@/api/commodity";
export default {
  name: "List",
  directives: {
    // 通过自定义指令实现的表单自动获得光标的操作
    focus: {
      inserted: function (el) {
        if (el.tagName.toLocaleLowerCase() === "input") {
          el.focus();
        } else {
          if (el.getElementsByTagName("input")) {
            el.getElementsByTagName("input")[0].focus();
          }
        }
        el.focus();
      },
    },
  },
  data() {
    return {
      types: [{ label: "All", value: "" }, ...this.storage.get("types")],
      currentPage: 1,
      total: 0,
      formInline: {
        page: 1,
        limit: 10,
        name: "",
        type: "",
        groupId: "",
        status: "",
      },
      activeName: "status",
      tableData: [],
      productGroupList: [{ productIds: "", groupName: "All" }],
      lockImgs: [
        require("@/assets/product/a0.jpg"),
        require("@/assets/product/a1.jpg"),
        require("@/assets/product/sd0.png"),
        require("@/assets/product/sd1.png"),
        require("@/assets/product/sd2.png"),
        require("@/assets/product/sd3.png"),
        require("@/assets/product/sd4.png"),
        require("@/assets/product/sd5.png"),
        require("@/assets/product/sd6.png"),
        require("@/assets/product/we0.png"),
        require("@/assets/product/we1.png"),
        require("@/assets/product/sd0.png"),
        require("@/assets/product/sd0.png"),
      ],
    };
  },
  created() {
    this.init();
    const groupList = this.storage.get("productGroupList").map((item) => {
      item.productIds =
        item.quantity.length > 0 ? item.quantity.toString() : "9999999999";
      return item;
    });
    this.productGroupList = [...this.productGroupList, ...groupList];
  },
  methods: {
    changeGroup(e) {},
    // 当input失去光标后进行的操作
    async blurInput(name, row) {
      let obj;
      this.tableData = this.tableData.map((item) => {
        if (row.id == item.id) {
          item.editPrice = false;
          item.editName = false;
          obj = item;
        }
        return item;
      });
      if (name === "price") {
        if (!row.price) {
          this.$message.error("Edit failure");
          this.init();
          return false;
        } else {
          if (parseInt(row.discountPrice) >= parseInt(row.price)) {
            this.$message.error(this.$t("createProduct.error3"));
            this.init();
            return false;
          } else {
            obj.price = row.price;
          }
        }
      }
      if (name === "name") {
        if (!row.name) {
          this.$message.error("Edit failure");
          this.init();
          return false;
        } else {
          obj.name = row.name;
        }
      }
      await saveCommodity({
        id: obj.id,
        name: obj.name,
        price: obj.price,
      });
      setTimeout(() => {
        this.$message({
          message: "Update successful",
          type: "success",
        });
        this.init();
      }, 500);
    },
    /*
			方法参数皆为框架方法的默认传参
			row 	行数据
			column	被点击的触发了方法的单元格
			event	事件
			*/
    tableDbEdit(row, column) {
      this.tableData = this.tableData.map((item) => {
        if (row.id === item.id) {
          if (column === "price") {
            item.editPrice = true;
          }
          if (column === "name") {
            item.editName = true;
          }
        }
        return item;
      });
    },

    seeDetail(row) {
      this.$confirm(
        row.status.value === "status1"
          ? this.$t("createProduct.onSaleTip")
          : this.$t("createProduct.offSaleTip"),
        this.$t("rulesManagement.tip"),
        {
          confirmButtonText: this.$t("rulesManagement.confirm"),
          cancelButtonText: this.$t("rulesManagement.cancel"),
          type: "warning",
        }
      )
        .then(async () => {
          if (row.status.value === "status0") {
            row.status = { value: "status1", label: "Off sale" };
          } else {
            row.status = { value: "status0", label: "On sale" };
          }
          await saveCommodity({
            id: row.id,
            status: JSON.stringify(row.status),
          });
          this.$message({
            message: this.$t("createProduct.editSuccess"),
            type: "success",
          });
          this.init();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("rulesManagement.canceled"),
          });
        });
    },
    addProduct() {
      this.$router.push({
        path: "createProduct",
      });
    },
    editProduct(id) {
      this.$router.push({
        path: "editProduct",
        // path: "createProduct",
        query: { id },
      });
    },
    handleSizeChange(val) {
      this.formInline.limit = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.formInline.page = val;
      this.init();
    },
    init() {
      let imgList =
        this.storage.get("imgList") || this.storage.set("imgList", []);
      getCommodityList(this.formInline).then((response) => {
        console.log(response);
        this.tableData = response.data;
        this.tableData = this.tableData.map((item) => {
          if (imgList && imgList.length > 0) {
            imgList.forEach((child) => {
              if (child !== null && child.id + "" == item.id + "") {
                item.img = child.img;
              }
            });
          }
          return item;
        });
        this.total = response.count;
      });

      //清除不存在的缓存图片
      let saveForm = {
        page: 1,
        limit: 999999,
        name: "",
        type: "",
        groupId: "",
        status: "",
      };
      getCommodityList(saveForm).then((response) => {
        console.log(response);
        let data = response.data;
        let saveImgList = [];
        if (imgList && imgList.length > 0) {
          imgList.forEach((child) => {
            for (let i = 0; i < data.length; i++) {
              if (child !== null && child.id + "" == data[i].id + "") {
                saveImgList.push(child);
              }
            }
          });
        }
        this.storage.set("commodityLength", data.length);
        this.storage.set("imgList", saveImgList);
      });
    },
    handleClick(tab, event) {
      if (tab.name === "status") {
        this.formInline.status = "";
      } else {
        this.formInline.status = tab.name;
      }
      this.formInline.page = 1;
      this.formInline.limit = 10;
      this.init();
    },
    onSubmit() {
      this.formInline.page = 1;
      this.formInline.limit = 10;
      this.init();
    },
  },
};
</script>

<style lang="scss" scoped>
.oldPrice span {
  color: #c0c4cc !important;
  text-decoration: line-through !important;
}
.addBtn {
  margin-bottom: 12px;
}
</style>
